package com.raincat.tools.multimediapickertools;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;
import com.raincat.tools.R;
import com.raincat.tools.multimediapickertools.utils.EasyActionBar;
import com.raincat.tools.multimediapickertools.utils.MultiMediaBucket;
import com.raincat.tools.multimediapickertools.utils.MultiMediaController;
import com.raincat.tools.multimediapickertools.utils.MultiMediaHelper;
import com.raincat.tools.multimediapickertools.utils.MultiMediaItem;

import java.util.ArrayList;
import java.util.List;

/**
 * <pre>
 *     author : RainCat
 *     org    : Shenzhen JingYu Network Technology Co., Ltd.
 *     e-mail : nining377@gmail.com
 *     time   : 2018/04/24
 *     desc   : 图片浏览
 *     version: 1.0
 * </pre>
 */

public class PicturesBrowseActivity extends AppCompatActivity {
    private Context context;

    private ViewPager viewPager;
    private EasyActionBar easyActionBar;
    private ImageView iv_original;
    private Button btn_sure;
    private TextView tv_original;
    private LinearLayout ll_picture_box;

    private List<MultiMediaItem> dataList = new ArrayList<>();
    private int checkIndex = -99;
    private int bucketIndex = -99;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        WindowManager.LayoutParams localLayoutParams = getWindow().getAttributes();
        localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
        setTheme(MultiMediaController.themeId);
        setContentView(R.layout.picker_activity_picturesbrowse);
        context = PicturesBrowseActivity.this;

        dataList = (List<MultiMediaItem>) getIntent().getSerializableExtra("List");
        checkIndex = getIntent().getIntExtra("CheckIndex", 0);
        bucketIndex = getIntent().getIntExtra("BucketIndex", -99);

        if (bucketIndex != -99) {
            getData();
        } else {
            Init();
            setData();
        }
    }

    public void Init() {
        iv_original = findViewById(R.id.iv_original);
        tv_original = findViewById(R.id.tv_original);
        btn_sure = findViewById(R.id.btn_sure);
        viewPager = findViewById(R.id.viewpager);
        ll_picture_box = findViewById(R.id.ll_picture_box);
        easyActionBar = findViewById(R.id.easyActionBar);
        easyActionBar.setTitleText((checkIndex + 1) + "/" + dataList.size());
        easyActionBar.setTitleRes(-1);
        easyActionBar.setRightLayoutVisibility(View.VISIBLE);
        easyActionBar.setImmerseLayout();

        if (MultiMediaController.multiMediaItemMap.get(dataList.get(checkIndex).path) == null)
            easyActionBar.setRightImageRes(false);
        else
            easyActionBar.setRightImageRes(true);

        listener();
    }

    private void getData() {
        MultiMediaHelper.getInstance(context).getMultiMediaBucketList(context, MultiMediaController.mode == 2, MultiMediaController.showGif, new MultiMediaHelper.onBucketListGetListener() {
            @Override
            public void onFinish(final List<MultiMediaBucket> bucketList) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (dataList == null)
                            dataList = new ArrayList<>();
                        dataList.addAll(bucketList.get(bucketIndex).multiMediaItemList);
                        //移除相机item
                        if (dataList.size() != 0 && dataList.get(0).path.equals(MultiMediaItem.CAMERA))
                            dataList.remove(0);
                        Init();
                        setData();
                    }
                });
            }
        });
    }

    private void setData() {
        setCount();
        refreshPictureBox();
        setOriginal();
        PagerAdapter pagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
        viewPager.setAdapter(pagerAdapter);
        viewPager.setCurrentItem(checkIndex);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {
                checkIndex = viewPager.getCurrentItem();
                easyActionBar.setTitleText((checkIndex + 1) + "/" + dataList.size());
                if (MultiMediaController.multiMediaItemMap.get(dataList.get(checkIndex).path) == null)
                    easyActionBar.setRightImageRes(false);
                else
                    easyActionBar.setRightImageRes(true);
            }
        });
    }

    private void listener() {
        easyActionBar.setOnRightLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setResult(RESULT_OK);
                if (MultiMediaController.addOrRemoveMultiMediaItem(context, dataList.get(viewPager.getCurrentItem()))) {
                    easyActionBar.setRightImageRes(true);
                } else {
                    easyActionBar.setRightImageRes(false);
                }
                refreshPictureBox();
                setCount();
            }
        });

        iv_original.setOnClickListener(new View.OnClickListener() {
            public void onClick(View paramAnonymousView) {
                setResult(RESULT_OK);
                MultiMediaController.isOriginal = !MultiMediaController.isOriginal;
                setOriginal();
            }
        });
        tv_original.setOnClickListener(new View.OnClickListener() {
            public void onClick(View paramAnonymousView) {
                setResult(RESULT_OK);
                MultiMediaController.isOriginal = !MultiMediaController.isOriginal;
                setOriginal();
            }
        });

        btn_sure.setOnClickListener(new View.OnClickListener() {
            public void onClick(View paramAnonymousView) {
                if (MultiMediaController.multiMediaItemMap.size() == 0)
                    MultiMediaController.addOrRemoveMultiMediaItem(context, dataList.get(viewPager.getCurrentItem()));
                if (MultiMediaController.mode == MultiMediaController.CROP) {
                    startActivityForResult(new Intent(context, CropActivity.class), PictureActivity.RESULT_CROP);
                } else {
                    finishActivity();
                }
            }
        });
    }

    private class ViewPagerAdapter extends FragmentStatePagerAdapter {
        ViewPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @NonNull
        @Override
        public Fragment getItem(int position) {
            PicturesBrowseFragment fragment = new PicturesBrowseFragment();
            fragment.setMultiMediaItem(dataList.get(position));
            return fragment;
        }

        @Override
        public int getCount() {
            return dataList.size();
        }
    }

    private void setCount() {
        if (btn_sure != null) {
            if (MultiMediaController.multiMediaItemMap.size() != 0) {
                btn_sure.setText(context.getResources().getString(R.string.picker_OK) + "(" + MultiMediaController.multiMediaItemMap.size() + "/" + MultiMediaController.maxCount + ")");
            } else {
                btn_sure.setText(context.getResources().getString(R.string.picker_OK));
            }
        }
        if (MultiMediaController.isOriginal) {
            tv_original.setText(context.getResources().getString(R.string.picker_original) + MultiMediaController.getImageSize());
        }
    }

    private void setOriginal() {
        if (!MultiMediaController.showOriginalOption) {
            iv_original.setVisibility(View.GONE);
            tv_original.setVisibility(View.GONE);
            return;
        }
        iv_original.setVisibility(View.VISIBLE);
        tv_original.setVisibility(View.VISIBLE);
        if (!MultiMediaController.isOriginal) {
            iv_original.setBackgroundResource(R.drawable.picker_check_disable);
            iv_original.setImageDrawable(null);
            tv_original.setText(context.getResources().getString(R.string.picker_original));
        } else {
            iv_original.setBackgroundResource(R.drawable.picker_check_enable);
            iv_original.setImageResource(R.mipmap.picker_check);
            tv_original.setText(context.getResources().getString(R.string.picker_original) + MultiMediaController.getImageSize());
        }
    }

    private void refreshPictureBox() {
        ll_picture_box.removeAllViews();
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        for (final MultiMediaItem item : MultiMediaController.multiMediaItemMap.values()) {
            View view = inflater.inflate(R.layout.picker_view_selectedpicture, null);
            ImageView iv_img = view.findViewById(R.id.iv_img);
            ImageView iv_delete = view.findViewById(R.id.iv_delete);
            Glide.with(context).asBitmap().load(item.path).into(iv_img);
            iv_img.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    for (int i = 0; i < dataList.size(); i++) {
                        if (dataList.get(i).path.equals(item.path))
                            viewPager.setCurrentItem(i);
                    }
                }
            });
            iv_delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    MultiMediaController.addOrRemoveMultiMediaItem(context, item);
                    if (MultiMediaController.multiMediaItemMap.get(dataList.get(checkIndex).path) == null)
                        easyActionBar.setRightImageRes(false);
                    else
                        easyActionBar.setRightImageRes(true);
                    setCount();
                    refreshPictureBox();
                }
            });
            ll_picture_box.addView(view);
        }
    }

    private void finishActivity() {
        Intent intent = new Intent();
        intent.putExtra("finish", true);
        setResult(RESULT_OK, intent);
        finish();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent paramIntent) {
        super.onActivityResult(requestCode, resultCode, paramIntent);
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureActivity.RESULT_CROP) {
                finishActivity();
            }
        }
    }

    protected void onDestroy() {
        Glide.get(this).clearMemory();
        System.gc();
        super.onDestroy();
    }
}
